package nckd.wnqjt.tmc.tda.plugin.form;

import java.util.*;

import com.alibaba.fastjson.JSON;
import kd.bos.ai.util.JsonUtil;
import kd.bos.algo.*;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.db.DB;
import kd.bos.db.DBRoute;
import kd.bos.entity.AppInfo;
import kd.bos.entity.AppMetadataCache;
import kd.bos.entity.qing.*;
import kd.bos.entity.qing.Field;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.form.IFormView;
import kd.bos.form.IPageCache;
import kd.bos.form.ShowType;
import kd.bos.form.control.IQingAnalysis;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.mvc.SessionManager;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.report.ReportShowParameter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;

/**
 * @author husheng
 * @date 2024-11-04 11:55
 * @description 动态表单插件      按授信类别分布
 */
public class CreditlimitTypeQingDataProvider extends AbstractFormPlugin implements IQingDataProvider {
    /**
     * 定义轻分析表头
     */
    @Override
    public QingMeta getMeta(String s) {
        String entityKey = "cfm_creditlimit";
        QingMeta meta = new QingMeta();
        EntryEntity entity = new EntryEntity();
        entity.setKey(entityKey);
        entity.setName(new LocaleString("PK"));
        entity.setPkFieldName("id");
        meta.addEntryEntity(entity);

        Field column = new Field();
        column.setEntity(entityKey);//字段所属实体key	否
        column.setKey("id");// 字段名(唯一标识)	是
        column.setFieldType(QingFieldType.Int.toNumber()); //数据类型	是
        column.setName(new LocaleString("id")); //字段别名	是
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("orgName");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("授信主体"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("t_totalamt");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("授信总额"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("t_useamt");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("已用额度"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("t_avaramt");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("可用额度"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("credittype");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("授信类别"));
        meta.addColumn(column);

        return meta;
    }

    /**
     * 获取轻分析数据，通过拿到过滤条件可以重新定义取数逻辑
     */
    @Override
    public QingData getData(String s, int i, int i1) {
        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter");
        if (qFilter != null) {
            //通过此方法拿到过滤参数
            Map<String, Object> filterParam = (Map) JSON.parseObject(qFilter, Map.class);
        }

        ORM orm = ORM.create();

        // 授信额度管理
        String creditlimitSql = "id,org,org.name orgName,org.number orgNumber,totalamt,useamt,avaramt," +
                "entry_type.id,entry_type.t_credittype,entry_type.t_totalamt,entry_type.t_useamt,entry_type.t_avaramt";
        QFilter filter = new QFilter("status", QCP.equals, "C")
                .and("enddate", QCP.large_than, this.getCurrentDate())
                .and("isclose", QCP.not_equals, "1");
        DataSet cfmCreditlimit = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_creditlimit", creditlimitSql, filter.toArray(), null);

        cfmCreditlimit = cfmCreditlimit.addNullField("credittype");

        DynamicObjectCollection creditlimit = orm.toPlainDynamicObjectCollection(cfmCreditlimit);

        // 授信类别
        DynamicObject[] cfm_credittypes = BusinessDataServiceHelper.load("cfm_credittype", "id,name", null, null);
        Map<Long, String> credittypeMap = new HashMap<>();
        Arrays.stream(cfm_credittypes).forEach(t -> {
            credittypeMap.put(t.getLong("id"), t.getString("name"));
        });

        creditlimit.stream().forEach(t -> {
            if (t.getLong("entry_type.t_credittype") != 0) {
                // 授信类别 多选基础资料
                StringBuffer stringBuffer = new StringBuffer("select t.fbasedataid from t_cfm_creditlimit_detai_d t where t.fentryid = ?");
                DataSet dataSet = DB.queryDataSet("t_cfm_creditlimit_detai_d", new DBRoute("tmc"), stringBuffer.toString(), new Object[]{t.getLong("entry_type.t_credittype")});
                DynamicObjectCollection dynamicObjects = orm.toPlainDynamicObjectCollection(dataSet);
                String name = credittypeMap.get(dynamicObjects.get(0).getLong("fbasedataid"));
                t.set("credittype", name);
            }
        });

        DataSet dataSet = buildDataByObjCollection("algoKey", cfmCreditlimit.getRowMeta().getFields(), creditlimit);

        dataSet = dataSet.filter("credittype is not null");

        QingData data = null;
        if (i < 200) {
            data = new QingData();
            Map<String, Integer> dataindex = new HashMap<>();
            dataindex.put("id", 0);
            dataindex.put("orgName", 1);
            dataindex.put("t_totalamt", 2);
            dataindex.put("t_useamt", 3);
            dataindex.put("t_avaramt", 4);
            dataindex.put("credittype", 5);
            data.setDataindex(dataindex);

            List<Object[]> rows = new ArrayList<>();
            while (dataSet.hasNext()) {
                Row row = dataSet.next();
                Object[] obj = new Object[6];
                obj[0] = row.getLong("id");
                obj[1] = row.getString("orgName");
                obj[2] = row.getBigDecimal("entry_type.t_totalamt");
                obj[3] = row.getBigDecimal("entry_type.t_useamt");
                obj[4] = row.getBigDecimal("entry_type.t_avaramt");
                obj[5] = row.getString("credittype");
                rows.add(obj);
            }
            data.setRows(rows);
        }

        return data;
    }


    //DynamicObjectCollection 转换为 DataSet 方法
    public DataSet buildDataByObjCollection(String algoKey, kd.bos.algo.Field[] rowFields, DynamicObjectCollection objCollection) {
        DataSetBuilder dataSetBuilder = Algo.create(algoKey + ".emptyFields")
                .createDataSetBuilder(new RowMeta(rowFields));
        for (DynamicObject arObj : objCollection) {
            Object[] rowData = new Object[rowFields.length];
            for (int i = 0; i < rowFields.length; i++) {
                kd.bos.algo.Field field = rowFields[i];
                rowData[i] = arObj.get(field.getName());
            }
            dataSetBuilder.append(rowData);
        }
        return dataSetBuilder.build();
    }

    @Override
    public void setFilterParameter(String filterParameter) {
        IPageCache pageCache = getPageCache();
        pageCache.put("qFilter", filterParameter);

    }

    @Override
    public String getFilterParameter() {
        return getPageCache().get("qFilter");
    }

    private Date getCurrentDate() {
        Calendar cal = new GregorianCalendar();
//        cal.set(11, 0);
//        cal.set(12, 0);
//        cal.set(13, 0);
//        cal.set(14, 0);
        return cal.getTime();
    }
}
